package com.pearadmin.edu.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.pearadmin.common.tools.sequence.SequenceUtil;
import com.pearadmin.common.web.base.BaseController;
import com.pearadmin.common.web.domain.response.Result;
import com.pearadmin.edu.enums.UserRoleEnum;
import com.pearadmin.edu.util.CoreUtil;
import com.pearadmin.edu.vo.SysUserVo;
import com.pearadmin.system.domain.SysDictData;
import com.pearadmin.system.domain.SysRole;
import com.pearadmin.system.domain.SysUser;
import com.pearadmin.system.service.ISysDictDataService;
import com.pearadmin.system.service.ISysRoleService;
import com.pearadmin.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/edu/user")
public class UserController extends BaseController {
    private String prefix = "edu/user";
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysDictDataService sysDictDataService;
    @Resource
    private ISysRoleService sysRoleService;

    /**
     * Describe: excel导入用户
     * Return 返回用户修改接口
     */
    @RequestMapping("/import")
    @ApiOperation(value = "excel导入用户")
    public Result importBatch(MultipartFile file) {

        //sysUserService.saveUserRole(sysUser.getUserId(), Arrays.asList(sysUser.getRoleIds().split(",")));
        //Boolean result = sysUserService.save(sysUser);
        StringBuilder sb = new StringBuilder();
        try {
            int startRow = 1;
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), 0);
            List<List<Object>> list = reader.read(startRow);
            // 进行非空和重复检查
            sb.append(CoreUtil.excelCheckBlank(list, startRow, 0, 4));
            sb.append(CoreUtil.excelCheckRepeat(list, startRow, 0));
            if (!sb.toString().isEmpty()) {
                return failure(sb.toString());
            }
            // 进行数据库层面检查
            List<SysUser> users = new ArrayList<>();
            List<SysRole> roles = new ArrayList<>();
            SysUser sysUser;
            SysRole sysRole;
            for (int i = 0; i < list.size(); i++) {
                List<Object> objects = list.get(i);
                // 账号
                String username = String.valueOf(objects.get(0));
                // 密码
                String password = String.valueOf(objects.get(1));
                // 用户名
                String nickName = String.valueOf(objects.get(2));
                // 性别
                String sexName = String.valueOf(objects.get(3));
                // 角色名
                String roleName = String.valueOf(objects.get(4));
                // 手机号
                String phone = String.valueOf(objects.get(5));
                // 邮箱
                String email = String.valueOf(objects.get(6));
                // 组织机构
                String orgName = String.valueOf(objects.get(7));
                //账号重复性
                sysUser = new SysUser();
                sysUser.setUsername(username);
                List<SysUser> userList = sysUserService.list(sysUser);
                if (userList != null && userList.size() > 0) {
                    sb.append("第");
                    sb.append(i + startRow + 1);
                    sb.append("行第列");
                    sb.append("账号不能重复;\r\n");
                    failure(sb.toString());
                }
                //性别转换成字典值
                SysDictData dictData = new SysDictData();
                dictData.setDataLabel(sexName);
                dictData.setTypeCode("sys_user_sex");
                List<SysDictData> sexDictData = sysDictDataService.list(dictData);
                if (sexDictData == null || sexDictData.size() == 0) {
                    sb.append("第");
                    sb.append(i + startRow + 1);
                    sb.append("行第4");
                    sb.append("列性别不存在;\r\n");
                } else {
                    sysUser.setSex(sexDictData.get(0).getDataValue());
                }
                //角色处理
                sysRole = new SysRole();
                sysRole.setRoleName(roleName);
                List<SysRole> sysRoleList = sysRoleService.list(sysRole);
                if (sysRoleList == null || sysRoleList.size() == 0) {
                    sb.append("第");
                    sb.append(i + startRow + 1);
                    sb.append("行第5");
                    sb.append("列角色不存在;\r\n");
                } else {
                    //保存下用户账号
                    sysRole.setCreateName(username);
                    sysRole.setRoleId(sysRoleList.get(0).getRoleId());
                    roles.add(sysRole);
                }
                sysUser.setRealName(nickName);
                sysUser.setLogin("0");
                sysUser.setEnable("1");
                sysUser.setStatus("1");
                sysUser.setUserId(SequenceUtil.makeStringId());
                sysUser.setCreateTime(LocalDateTime.now());
                sysUser.setPassword(new BCryptPasswordEncoder().encode(password));
                users.add(sysUser);
            }
            if (!sb.toString().isEmpty()) {
                return failure(sb.toString());
            }
            // 开始添加用户
            int okNum = 0, errorNum = 0;
            for (SysUser user : users) {
                if (sysUserService.save(user)) {
                    SysUser userTemp = sysUserService.list(user).get(0);
                    List<String> roleList = roles.stream().filter(role -> role.getCreateName() == user.getUsername()).map(SysRole::getRoleId).collect(Collectors.toList());
                    sysUserService.saveUserRole(userTemp.getUserId(), roleList);
                    okNum++;
                } else {
                    errorNum++;
                }
            }
            return success("导入完成，成功" + okNum + "条，失败" + errorNum + "条");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success(true);
    }

    /**
     * 获取教员
     *
     * @return
     */
    @GetMapping("/getTeacherList")
    @ApiOperation(value = "获取教员")
    public Result getTeacherList() {
        List<SysUser> userList = sysUserService.getUserByRole(UserRoleEnum.teacher.getName());
        return Result.success(userList);
    }

    /**
     * 获取用户信息
     * @param id
     * @return
     */
    @GetMapping("/getUserById")
    public Result getUserById(String id) {
        if(StringUtils.isBlank(id)){
            return failure();
        }
        SysUser user = sysUserService.getById(id);
        String realName=user.getRealName();
        return Result.success(realName);
    }
}
